<?php
/**
 * RedCross Application
 *
 * @copyright Copyright (c) 2010, Kristian Stokke Tryggestad, Rune Vikestad, Andreas Flaten Wist, Simen Nicolai Echholt, Ole Henrik Jahren
 */


class RedCross_View_Helper_FlashMessage extends Zend_View_Helper_Abstract
{
    const ERROR = 'message_error';
    const INFO = 'message_info';
    const WARNING = 'message_warning';
    const SUCCESS = 'message_success';

    private $_flashMessenger;

    public function flashMessage()
    {
        $this->_flashMessenger = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger');
        return $this;
    }

    public function addMessage($message, $code = self::INFO)
    {
        $this->_flashMessenger->addMessage(array($message, $code));
    }

    public function getMessages()
    {
        if (!$this->_flashMessenger->hasMessages()) {
        	return array();
        }

        $flashMessages = $this->_flashMessenger->getMessages();
        return $this->_formatMessages($flashMessages);
    }

    public function getCurrentMessages()
    {
        if (!$this->_flashMessenger->hasCurrentMessages()) {
        	return array();
        }

        $flashMessages = $this->_flashMessenger->getCurrentMessages();
        return $this->_formatMessages($flashMessages);
    }

    private function _formatMessages (array $flashMessages)
    {
        $messages = array();
        foreach ($flashMessages as $message) {
        	if (!is_array($message)) {
        		$messages[] = array('message' => $message, 'code' => self::INFO);
        	} else if (!array_key_exists('message', $message) && count($message) == 2) {
        		$messages[] = array('message' => $message[0], 'code' => $message[1]);
        	} else {
        	    $messages[] = $message;
        	}
        }
        return $messages;
    }

    public function renderMessage($message, $code) 
    {
        $array = array('message' => $message, 'code' => $code);
        return $this->_render(array($array));
    }

    public function renderMessages()
    {
        return $this->_render($this->getMessages());
    }

    public function renderCurrentMessages()
    {
        return $this->_render($this->getCurrentMessages());
    }

    private function _render(array $messages)
    {
        if ($messages === array()) {
        	return;
        }
        $this->view->addScriptPath(APPLICATION_PATH . '/layouts/main/partials/');
        return $this->view->partial('flashMessageDisplayer.phtml', array('messages' => $messages));
    }


}
